import React, {Component} from 'react';
import {
    View,
    Text,
    Image,
    Button,
    ListView,
    ScrollView,
    StyleSheet,
} from 'react-native';
import ScrollableTabView, { ScrollableTabBar, } from 'react-native-scrollable-tab-view';
import Scroller from '../../components/Scroller';
import CreationItem from '../../components/CreationItem';

// 缓存列表中所有数据
let cachedResults = {
    nextPage: 1, // 下一页
    items: [], // listview 数据(视频列表)
    total: 0 // 总数
};
export default class NewsPage extends Component {
    /*static navigationOptions = {
        title: '新闻',
        
    };*/
    constructor(props) {
        super(props);
        let ds = new ListView.DataSource({
            // 比较两条数据是否是一样的,来判断数据是否发生改变
            rowHasChanged: (r1, r2) => r1 !== r2
        });
        this.state = {
            dataSource: ds.cloneWithRows([]),
            isLoadingTail: false, // loading?
            isRefreshing: false, // refresh?
            tabShow: false,
            label:['tab#1','tab#2','tab#3','tab#4','tab#5','tab#6','tab#7']
        };
    }// 生命周期-组件挂载完毕 请求数据
    componentDidMount() {
        setTimeout(() => {
            this.setState({
                tabShow: true 
            });
        }, 0)
        this._fetchData(1);
    }

    // 请求数据
    _fetchData(pageSize) {

        if (pageSize !== 0) { // 加载更多操作
            this.setState({
                isLoadingTail: true
            });
        } else { // 刷新操作
            this.setState({
                isRefreshing: true
            });
            // 初始哈 nextPage
            cachedResults.nextPage = 2;
        }

        fetch(`http://api.midoogame.com/stat/gamelist?fromtype=1&page=${pageSize}&type=0`)
            // data 变化的新数据
            .then(resp => {
                resp.json().then(({ data: { gamelist, typearr, page } }) => {

                    if (gamelist.length != 0) {
                        // 保存原数据
                        let items = cachedResults.items.slice();
                        if (pageSize !== 0) { // 加载更多操作
                            console.log('加载更多:', items)
                            // 数组拼接
                            items = items.concat(gamelist);
                            cachedResults.nextPage += 1;
                        } else { // 刷新操作
                            console.log('刷新:', items)
                            // 数据不变
                            items = gamelist;
                        }

                        cachedResults.items = items; // 视频列表数据
                        cachedResults.total = page.total; // 总数

                        setTimeout(() => {
                            if (pageSize !== 0) { // 加载更多操作
                                this.setState({
                                    isLoadingTail: false,
                                    dataSource: this.state.dataSource.cloneWithRows(cachedResults.items)
                                });
                            } else { // 刷次操作
                                this.setState({
                                    isRefreshing: false,
                                    dataSource: this.state.dataSource.cloneWithRows(cachedResults.items)
                                });
                            }
                        }, 1000);
                    }/**/
                })
            })
            .catch((error) => {
                if (pageSize !== 0) { // 上拉加载更多操作
                    this.setState({
                        isLoadingTail: false
                    });
                } else {
                    this.setState({ // 刷新操作
                        isRefreshing: false
                    });
                }
                console.error(error);
            });
    }

    // 列表 Item
    _renderRow(row) {
        const { navigation } = this.props;
        return (
            <CreationItem
                navigation={navigation}
                //key={row.id} 子组件唯一性
                row={row}
            />
        )
    }
    render() {
        //if (this.state.tabShow){}此判断用于解决在首页不显示问题
        let {label}=this.state;
            return (
                <ScrollableTabView
                scrollWithoutAnimation={true}
                tabBarUnderlineStyle={styles.tabUnderline}
                //tabBarBackgroundColor='#fff'
                tabBarActiveTextColor='#b4282d'
                tabBarInactiveTextColor='#333'
                initialPage={2}
                renderTabBar={() => <ScrollableTabBar/>}>
                    {
                        label.map((el,ind)=>
                            <Scroller
                                tabLabel={el}
                                
                                key={ind}
                                // 数据源
                                dataSource={this.state.dataSource}
                                // 渲染item(子组件)
                                renderRow={this._renderRow.bind(this)}
                                // 是否可以刷新
                                isRefreshing={this.state.isRefreshing}
                                // 是否可以加载更多
                                isLoadingTail={this.state.isLoadingTail}
                                // 请求数据
                                fetchData={this._fetchData.bind(this)}
                                // 缓存列表数据
                                cachedResults={cachedResults}
                            />
                        )
                    }
                    
                </ScrollableTabView>
            );
        
    }
}
/**<ScrollView  tabLabel={el} key={ind}>
                                <Text>{el}</Text>
                                <Image source={{uri:'http://via.placeholder.com/500x1000'}} style={styles.img}/>
                            </ScrollView >
 * <ScrollView  tabLabel='Tab #2'>
        <Text>Tab #2</Text>
        <Image source={{uri:'http://via.placeholder.com/500x1000'}} style={styles.img}/>
    </ScrollView >
    <ScrollView  tabLabel='Tab #3'>
        <Text>Tab #3</Text>
        <Image source={{uri:'http://via.placeholder.com/500x1000'}} style={styles.img}/>
    </ScrollView >
    <ScrollView  tabLabel='Tab #4'>
        <Text>Tab #4</Text>
        <Image source={{uri:'http://via.placeholder.com/500x1000'}} style={styles.img}/>
    </ScrollView >
    <ScrollView  tabLabel='Tab #5'>
        <Text>Tab #5</Text>
        <Image source={{uri:'http://via.placeholder.com/500x1000'}} style={styles.img}/>
    </ScrollView >
 */
const styles = StyleSheet.create({
    container: {
        flex: 1,
        //flexDirection: 'column',
        justifyContent: 'center',
        alignItems: 'center',
    },
    tabUnderline:{
        backgroundColor:'red',
        height:2
    },
    img:{
        flex:1,
        justifyContent:'center',
        width:500,
        height:1000
    }
});